# -*- coding: utf-8 -*-
# -----------------------------------------
# @Time       : 2021/2/19 13:13
# @Author     : dqz 
# @Email      : 1406990390@qq.com
# @File       : host.py
# @Software   : PyCharm
# -----------------------------------------
import ipaddress
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from utils.dir_files import DirFile
from utils.parase import ParseConf
from concurrent.futures import ProcessPoolExecutor, as_completed  # ,ThreadPoolExecutor
from utils.base import Monitor
from utils.ding import Ding
from utils.feishu import FeiShu
from config.settings import MAX_WORKER, FILE_CONFIG_FILTER


class App:
    def __init__(self):
        pass

    def start(self):
        """
        1. 获取file
        2. 获取file_info
        3. check and send dingding
        :return:
        """
        dir_path, files = self.get_dir_and_files()
        files_info = self.get_files_info(dir_path, files)
        self.check_files_info(files_info)

    def get_dir_and_files(self):
        op_files = DirFile()
        dir_path = op_files.get_dir()
        files = op_files.get('host')
        return dir_path, files

    def get_files_info(self, dir_path, files):
        files_info = {}
        for file in files:
            path = os.path.join(dir_path, file)
            parse = ParseConf(path)
            files_info[file] = parse.get_sections_info()

        return files_info

    def check_files_info(self, files_info):
        if not files_info:
            return None
        tasks = []
        with ProcessPoolExecutor(max_workers=MAX_WORKER) as executor:
            for file, infos in files_info.items():
                for section, options in infos.items():
                    if "default" == section:
                        continue

                    try:
                        self.check_and_send_msg(section, options)
                        #task = executor.submit(self.check_and_send_msg, section, options)
                        #tasks.append(task)
                    except Exception as e:
                        continue

            for task in as_completed(tasks):
                try:
                    task.result()
                except Exception as e:
                    print(e)

    def check_and_send_msg(self, section, options):
        if "dingtoken" not in options.keys():
            token = options["feishutoken"]
            ding = FeiShu(token)
        else:
            token = options["dingtoken"]
            ding = Ding(token)
        rsa_path = options["rsa_path"]

        monitor = Monitor()
        for ip, desc in options.items():
            if ip in FILE_CONFIG_FILTER:
                continue
            try:
                # 过滤非ip
                if not ipaddress.ip_address(ip):
                    continue

                limit = 90
                cpu_info = monitor.cpu(ip, rsa_path, env=section, limit=limit)
                print(f"cpu:{cpu_info}")
                if not cpu_info["status"]:
                    ding.send_text(section, f"{ip}={desc} check cpu_ideal {cpu_ideal['data']}% < {100 - limit}%, please check it")

                limit = 95
                disk_info = monitor.disk(ip, rsa_path, env=section, limit=limit)
                print(f"disk: {disk_info}")
                if not disk_info["status"]:
                    ding.send_text(section, f"{ip}={desc} check disk_use {disk_info['data']}% > {limit}%, please check it")

                limit = 200
                memory_info = monitor.memory(ip, rsa_path, env=section, limit=limit)
                print(f"memory: {memory_info}")
                if not memory_info["status"]:
                    ding.send_text(section, f"{ip}={desc} check memory_ideal {memory_info['data']}mb < {limit}mb, please check it")

            except Exception as e:
                print(e)


if __name__ == "__main__":
    app = App()
    app.start()
